package com.fanyu.framework.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.*;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClients4 {
    private int connectTimeout = 30000;
    private int readTimeout = 30000;
    private String requestCharset = "utf-8";
    private String responseCharset = "utf-8";
    private BasicCookieStore cookieStore;
    private CloseableHttpClient httpclient;

    public HttpClients4() {
        HttpClientBuilder builder = HttpClients.custom();
        this.cookieStore = new BasicCookieStore();
        builder = builder.setDefaultCookieStore(this.cookieStore);

        try {
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory((new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustSelfSignedStrategy()).build(), new String[] {"TLSv1.2"}, (String[])null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            builder = builder.setSSLSocketFactory(sslsf);
        } catch (Exception var3) {
        }

        this.httpclient = builder.build();
    }

    public HttpClients4(int connectTimeout, int readTimeout) {
        this.connectTimeout = connectTimeout;
        this.readTimeout = readTimeout;
        HttpClientBuilder builder = HttpClients.custom();
        this.cookieStore = new BasicCookieStore();
        builder = builder.setDefaultCookieStore(this.cookieStore);

        try {
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory((new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustSelfSignedStrategy()).build(), new String[] {"TLSv1.2"}, (String[])null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            builder = builder.setSSLSocketFactory(sslsf);
        } catch (Exception var5) {
        }

        this.httpclient = builder.build();
    }

    public HttpClientResult get(String url) {
        return this.get(url, (Map)null);
    }

    public HttpClientResult get(String url, Map<String, String> headers) {
        CloseableHttpResponse response = null;
        HttpGet httpget = new HttpGet(url);

        HttpClientResult var17;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout).setConnectTimeout(this.connectTimeout).build();
            httpget.setConfig(requestConfig);
            if (headers != null && !headers.isEmpty()) {
                Iterator var6 = headers.entrySet().iterator();

                while (var6.hasNext()) {
                    Entry<String, String> e = (Entry)var6.next();
                    if (StringUtils.isNotBlank((CharSequence)e.getKey()) && StringUtils.isNotBlank((CharSequence)e.getValue())) {
                        httpget.addHeader((String)e.getKey(), (String)e.getValue());
                    }
                }
            }

            response = this.httpclient.execute(httpget);
            var17 = new HttpClientResult(response);
        } catch (Exception var16) {
            throw new RuntimeException("GET failure. " + var16.getMessage(), var16);
        } finally {
            httpget.abort();
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException var15) {
                        throw new RuntimeException("GET CLOSE failure. " + var15.getMessage(), var15);
                    }
                }
            }

        }

        return var17;
    }

    public HttpClientResult post(String url) {
        return this.post(url, (Map)null, (Map)null, false);
    }

    public HttpClientResult post(String url, Map<String, Object> params) {
        return this.post(url, (Map)null, params, false);
    }

    public HttpClientResult postFile(String url, Map<String, Object> params) {
        return this.post(url, (Map)null, params, true);
    }

    public HttpClientResult post(String url, Map<String, String> headers, Map<String, Object> params, boolean hasFile) {
        CloseableHttpResponse response = null;
        HttpPost httppost = new HttpPost(url);

        HttpClientResult var22;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout).setConnectTimeout(this.connectTimeout).build();
            httppost.setConfig(requestConfig);
            if (headers != null && !headers.isEmpty()) {
                Iterator var8 = headers.entrySet().iterator();

                while (var8.hasNext()) {
                    Entry<String, String> e = (Entry)var8.next();
                    if (StringUtils.isNotBlank((CharSequence)e.getKey()) && StringUtils.isNotBlank((CharSequence)e.getValue())) {
                        httppost.addHeader((String)e.getKey(), (String)e.getValue());
                    }
                }
            }

            Entry e;
            Iterator var23;
            if (hasFile) {
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(StandardCharsets.UTF_8);
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (params != null) {
                    var23 = params.entrySet().iterator();

                    while (var23.hasNext()) {
                        e = (Entry)var23.next();
                        if (!StringUtils.isBlank((CharSequence)e.getKey())) {
                            System.out.println("e.key-------------" + e.getKey() + "----------e.value-----------" + e.getValue());
                            if (e.getValue() instanceof File) {
                                builder.addPart((String)e.getKey(), new FileBody((File)e.getValue()));
                            } else {
                                builder.addPart((String)e.getKey(),
                                    new StringBody(e.getValue() == null ? "" : e.getValue().toString(), ContentType.create("application/x-www-form-urlencoded", Charset.forName(this.requestCharset))));
                            }
                        }
                    }
                }

                HttpEntity entity = builder.build();
                httppost.setEntity(entity);
            } else {
                List<NameValuePair> nvps = new ArrayList<>();
                if (params != null) {
                    var23 = params.entrySet().iterator();

                    while (var23.hasNext()) {
                        e = (Entry)var23.next();
                        if (!StringUtils.isBlank((CharSequence)e.getKey())) {
                            nvps.add(new BasicNameValuePair((String)e.getKey(), e.getValue() == null ? null : e.getValue().toString()));
                            System.out.println(e.getKey() + "---------------" + e.getValue());
                        }
                    }
                }

                httppost.setEntity(new UrlEncodedFormEntity(nvps, this.requestCharset));
            }

            response = this.httpclient.execute(httppost);
            var22 = new HttpClientResult(response);
        } catch (Exception var20) {
            throw new RuntimeException("POST failure. " + var20.getMessage(), var20);
        } finally {
            httppost.abort();
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException var19) {
                        throw new RuntimeException("POST CLOSE failure. " + var19.getMessage(), var19);
                    }
                }
            }

        }
        return var22;
    }

    public HttpClientResult post(String url, Map<String, String> headers, String body) {
        CloseableHttpResponse response = null;
        HttpPost httppost = new HttpPost(url);

        HttpClientResult var18;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout).setConnectTimeout(this.connectTimeout).build();
            httppost.setConfig(requestConfig);
            if (headers != null && !headers.isEmpty()) {
                Iterator var7 = headers.entrySet().iterator();

                while (var7.hasNext()) {
                    Entry<String, String> e = (Entry)var7.next();
                    if (StringUtils.isNotBlank((CharSequence)e.getKey()) && StringUtils.isNotBlank((CharSequence)e.getValue())) {
                        httppost.addHeader((String)e.getKey(), (String)e.getValue());
                    }
                }
            }

            httppost.setEntity(new InputStreamEntity(new ByteArrayInputStream(body.getBytes(this.requestCharset))));
            response = this.httpclient.execute(httppost);
            var18 = new HttpClientResult(response);
        } catch (Exception var17) {
            throw new RuntimeException("POST failure. " + var17.getMessage(), var17);
        } finally {
            httppost.abort();
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException var16) {
                        throw new RuntimeException("POST CLOSE failure. " + var16.getMessage(), var16);
                    }
                }
            }

        }

        return var18;
    }

    public void close() {
        if (this.httpclient != null) {
            try {
                this.httpclient.close();
            } catch (IOException var2) {
            }
        }

    }

    public int getConnectTimeout() {
        return this.connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getReadTimeout() {
        return this.readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public String getRequestCharset() {
        return this.requestCharset;
    }

    public void setRequestCharset(String requestCharset) {
        this.requestCharset = requestCharset;
    }

    public String getResponseCharset() {
        return this.responseCharset;
    }

    public void setResponseCharset(String responseCharset) {
        this.responseCharset = responseCharset;
    }

    public class HttpClientResult {
        private int status;
        private Charset charset;
        private Map<String, String> headers;
        private List<Cookie> cookies;
        private byte[] body;

        public HttpClientResult(CloseableHttpResponse response) {
            this.status = response.getStatusLine().getStatusCode();
            this.headers = new HashMap<>();
            Header[] hs = response.getAllHeaders();

            for (int i = 0; i < hs.length; ++i) {
                this.headers.put(hs[i].getName(), hs[i].getValue());
            }

            try {
                ContentType contentType = ContentType.get(response.getEntity());
                if (contentType != null) {
                    this.charset = contentType.getCharset();
                }

                this.cookies = HttpClients4.this.cookieStore.getCookies();
                this.body = EntityUtils.toByteArray(response.getEntity());
            } catch (IOException var5) {
                throw new RuntimeException("response read failure. " + var5.getMessage(), var5);
            }
        }

        public int getStatus() {
            return this.status;
        }

        public Map<String, String> getHeaders() {
            return this.headers;
        }

        public List<Cookie> getCookies() {
            return this.cookies;
        }

        public InputStream getBodyAsStream() {
            if (this.body != null) {
                InputStream byteResponseStream = new ByteArrayInputStream(this.body);
                return byteResponseStream;
            } else {
                return null;
            }
        }

        public byte[] getBody() {
            return this.body;
        }

        public String getBodyAsString() {
            if (this.charset != null) {
                return new String(this.body, this.charset);
            } else {
                try {
                    return new String(this.body, HttpClients4.this.responseCharset);
                } catch (Exception var2) {
                    throw new RuntimeException("toString. " + var2.getMessage(), var2);
                }
            }
        }
    }
}
